\appendix
\chapter{Native Joystick Libraries and Their Compilation}
\label{A:chap:JNI}
\section{JNI Description}
JNI is a~powerful feature of the~Java platform. Application that use the~JNI can
incorporate native code written in programming languages such as C and
C++.\cite{Liang:1999:JNI:520155}

Java platform has its beauty in the~level of abstraction from the~hardware,
from the~underlying operating system and its resources. This can be very
convenient but once there is either legacy native code that is worth to be used
or there is need to acutally access the~native resources or details of the
underlying OS, JNI allows the~developer to cross the~boundary of the~Java
encapsulation. Once using this powerful tool, developer takes responsibility for
all the~technical details of his actions plus he has to strictly follow rules of
the JNI.

One thing that is useful to know when working with JNI. It is extremely
dangerous and hard to debug. Once you access some resource that is not available
or you try to write to some part of memory which is not permitted to be written
to, application fails immediately. The~only place to look for some clues is the
VM core dump. There are no \texttt{UncaughtExceptionHandler} or any other of
these cool features of interpreted languages.

JNI is capable of invoking a~native method from the~Java code and also the~other
way around. Actually both cases are used in this project as will be described
later. It is capable of running native threads. It can pass primitives, arrays
and Strings as parameters or return values. It can handle access to fields and
methods of objects.

\subsection{Method Signatures}

Methods of the~native library that are mapped to the~methods of the~Java must
comply with the~signatures. Rules of the~method's signatures are complex and
fortunatelly JDK comes with a convenient tool called \texttt{javah}. This tool
when executed with some Java class as a~parameter, creates a~C header file
(``.h'') which is compliant with the~given Java class. There are two catches
when using this tool that can take few hours for the~beginners to resolve.

First is that this tool works on ``*.class'' files, not ``*.java'' files. You
have to compile the~code first using \texttt{javac} command or any other Java
compiler.

Second one is that you have to specify the~fully qualified name of the~class. If
you have a~class located in package \texttt{org.mycompany.myproject} and the
class is called \texttt{MyClass} you have to specify the~name as
\texttt{org.mycompany.myproject.MyClass}. This might be obvious. There is one
implication to this naming issue. Once you specify the~path like this
\texttt{javah} tool will be searching for the~class in the~hirearchy of
subfolders. So basically if your current working directory is
\texttt{/home/user1/project} the~tool will be searching for the~class in the
path of \texttt{/home/user1/project/org/mycompany/myproject/MyClass.class}.

\subsection{Callbacks}
Calling of the~Java code from the~native code can be achived by using the~method
from the~\texttt{JNIEnv} object. In each native method, pointer to this object
is available. Let's assume that we have a~situation according to code snippet in
algorithm \ref{fig:JNICallback}. As you can see, call is realized by
\texttt{CallVoidMethod} method on the~\texttt{JNIEnv} instance. There are
respective methods for boolean, String and other cases. To call a~method we have
to have its signature first. To get the~signature of a~method, we have to get
a signature of a~class. These parts are somehow obvious from the~snippet. What
might be confusing is the~\texttt{(III)V} part.

\begin{algorithm}
  \caption{Callbacks to the~Java code from a~native code using JNI}
  \label{fig:JNICallback}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true,language=C]
JNIEXPORT void JNICALL
Java_org_mycompany_myproject_MyClass_niceMethod (JNIEnv * env, jobject callback)
{ 
...
jclass callbackClass = (*env)->GetObjectClass(env, callback);
jmethodID callbackMethod = (*env)->GetMethodID(env, callbackClass, "callback",
"(III)V"); 
if (doCloseMethod == NULL) { 
	printf("Cannot find signature of callback method!");
	return; /* method not found */
(*env)->CallVoidMethod(env, callback, callbackMethod, firstIntVar, secondIntVar,
thirdIntVar);
...
}

\end{lstlisting}       
\end{algorithm}

This string represents a~list of arguments and returning type of the~method and
it is refered to as the~method descriptor. It is constructed as a~list of
parameter types in the~brackets and return type after that. If there are no
parameters, brackets will be empty. If the~method has void as its return type,
letter V will be used as it is in the~example. There are single-letter shortcuts
for primitives. Signature can also contain objects. In that case this is how it
can look like \texttt{([Ljava/lang/String;)Ljava/lang/String;}. Descriptor for
arrays start with the~square bracket.

JDK comes with another useful tool which can print the~method descriptors. It is
called \texttt{javap}. Invocation and possible result are shown in the~algorithm
\ref{fig:JNIjavap}.

\begin{algorithm}
  \caption{Invocation and Result of the~javap Tool}
  \label{fig:JNIjavap}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true]
javap -s -p MyClass
...
public callback (III)V
public anotherMethod ([Ljava/lang/String;)Ljava/lang/String;
...
\end{lstlisting}       
\end{algorithm}

\subsection{Compiling the~Native Code}
Your native code has to be compiled into the~shared library before it can be
loaded and used in the~application. The~procedure differs for Windows and Linux.

On Linux you might want to use the~\texttt{gcc}\footnote{The GNU Compiler
Collection - \url{http://gcc.gnu.org}} compiler.

\begin{algorithm}
  \caption{Compilation of the~JNI Code on Linux}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true]
gcc -c -fPIC -I<path to your JDK dir>/include -I<path to your JDK
dir>/include/linux JNILibrary.c
gcc -shared -W1,-soname,libjnilibrary.so -o libjnilibrary.so JNILibrary.o
\end{lstlisting}       
\end{algorithm}

On Windows you can stick to the~gcc or you
can use \texttt{cl}, compiler that comes with the~Microsoft C++ Visual Studio
.NET and do the~compilation using the~IDE. The~other option is to go with
MinGW\footnote{MinGW - Minimalist GNU for Windows - \url{http://www.mingw.org/}}
project and use \texttt{gcc} (or \texttt{g++} in this case).
There is actually also project
MinGW-w64\footnote{\url{http://mingw-w64.sourceforge.net/}} which provides also
the 64 bit support. Example of the~library compilation using the~MinGW follows
in algorithm \ref{alg:JNIWin}.

\begin{algorithm}
  \caption{Compilation of the~JNI Code on Windows}
  \label{alg:JNIWin}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true]
g++ -static-libgcc -static-libstdc++ -Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at -I"C:\Program Files\Java\jdk1.7.0_10\include" -I"C:\Program Files\Java\jdk1.7.0_10\include\win32" -shared robotPlaygroundJoystick.cpp -lwinmm -o robotPlaygroundJoystick.dll
\end{lstlisting}       
\end{algorithm}


\subsection{Loading of the~Native Libraries}
Inside the~class containing the~native methods, the~native library must be
loaded before the~native methods can be accessed. This is usually done in the
static initializer. There is the~\texttt{System.loadLibrary(String libraryName)}
method for libraries loading. One important thing is to provide the~library name
in the~platform independent form. If you have library ``mylibrary'', the~binary
file on Linux will be called ``libmylibrary.so''. On Windows it will be
``mylibrary.dll''. Still you will provide only ``mylibrary'' as a~parameter.
Java will decide what to search for in the~runtime based on the~environment.
Loading a~library requires to have this library available on the~classpath. How
to add the~library onto the~classpath inside the~Eclipse Plugin will be
discussed in the~next section.


\subsection{Bundling Native Libraries into the~Eclipse Plugins}
To bundle the~native library into the~Eclipse Plugin, it has to be located
inside of this plugin. To achieve this, add the~location of the~library to the
``build'' tab of the~bundle manifest.

Second part is to add it to the~runtime classpath. To do this, open the~bundle
manifest in the~text editor and add line similar to the~algorithm
\ref{fig:JNIAddingToManifest}.

\begin{algorithm}
  \caption{Adding a~Native Library to the~Bundle Manifest}
  \label{fig:JNIAddingToManifest}
\begin{lstlisting}[basicstyle={\scriptsize\ttfamily},breaklines=true]
Bundle-NativeCode: native/linux64/libmylibrary.so; osname=Linux;
processor=x86_64, native/win32/mylibrary.dll; osname=win32; processor=x86
\end{lstlisting}       
\end{algorithm}

Two important points. At this point the~name of the~library must be a~complete
filename rather than the~platform independent form. You can use ``osname'' and
``processor'' directives to bundle multiple libraries into one plugin. Only
appropriate libraries will be loaded in the~runtime. 

If you don't want to bundle all native binaries into one plugin, you can use
fragments. As discussed before, fragment transparently expands the~classpath of
the host plugin. You can specify the~platform filter for whole fragment. Only
appropriate fragments will be bundled when exporting whole product. This might
be useful when the~native code is rather extensive and you don't want users to
download unnecessary weight.

\section{Linux Implementation of the~Joystick Device}
In Linux there is the~Joystick manipulation library which is very convenient for
our purpose. It is implemented as a~device from which we just read. We can
choose between the~blocking and non-blocking reading. Openning and closing of
the device is rather simple thanks to the~file descriptor nature of the~access.

\subsection{Reading of Device Signature}
Device signature can be read by calling \texttt{ioctl} function with the
\texttt{JSIOCGNAME(80)} code on the~file descriptor of the~device. Thanks to the
differences between Strings handling in the~C and Java,
\texttt{(*env)->NewStringUTF(env, joystickName)} must be returned rather than~just returning the~array of chars.

\subsection{Reading of Device Events}
By calling the~\texttt{read} method on the~device file descriptor, we get a
structure \texttt{js\_event}. This structure holds information about the~last
event of the~device. We can use its \texttt{type} attribute to find out what was
the cause of last change, if it was a~change in the~axis value or a~change in
the buttons state. 

It is useful to note the~latest value of the~\texttt{time} attribute and perform
the callback to the~Java code only if this value varies from the~last reading to
avoid unnecessary workload of the~application.

In my implementation, this reading is performed periodically in the~loop with
sleep element inside. At each iteration, state of the~close flag is checked and
if the~flag is set, loop is terminated. While the~read is in the~non-blocking
mode, reaction takes one iteration in the~worst case scenario.

\section{Windows Implementation of the~Joystick Device}
MS Windows come with a~fairly good joystick support. They provide new
DirectInput API, that is a~little bit too complex for this occassion.
Fortunatelly their ``Legacy Audio and Video'' libraries are simple and provide
all the~functionality needed for this project. Through the~text I~was talking
about the~JNI parts of the~application being implmemented using the~C language.
Actually due to the~nature of MS Windows API, C++ was used in this case.

Functionality is located in the~\texttt{Winmm.dll} and covered in
\texttt{Mmsystem.h} header file. It should be enough to include only
\texttt{Windows.h} header file. Surprisingly although there is a~possibility to
capture a~joystick to send its messages only to the~specific window, there is
no real need to capture the~device in this project.

\subsection{Reading the~Device Signature}
Device signature can be obtained by calling a~\texttt{joyGetDevCaps} function.
This function takes pointer to the~structure which will be filled by the~result
and returns the~error code or 0 if everything runs smoothly. Among other useful
information, name of the~device is hidden inside of this structure.
Unfortunatelly the~only result I've got during the~testing phase was some
generic name given by the~system driver. String returned by this call is
actually represented by an~array of \texttt{TCHAR} type and must be converted
before it can be returned as \texttt{jstring} from the~JNI.

\subsection{Reading the~Device State}
The state of the~device can be accessed using the~\texttt{joyGetPos} function.
Again this function takes a~pointer to the~structure into which it writes its
results and returns an~error code. Unlike Linux event concept, information are
accessed periodically in the~loop with some delay between iterations. The
complete state of the~joystick is gathered in one call. To comply with the
concept in this project, several callbacks need to be performed in order to
provide the~necessary information. Ranges of axis and buttons are equal to the
Linux variant.

\chapter{User's Guide}
\label{A:chap:usersGuide}
\input{userGuide}
\chapter{Developer's Guide to the~Points of Extension}
\label{A:chap:developersGuide}
\input{developerGuide}
\chapter{Content of the~Enclosed CD}
\label{A:chap:CDContent}

\begingroup
\inputencoding{latin1}
\begin{lstlisting}[basicstyle={\footnotesize\ttfamily},breaklines=true]
|-- install.txt - Instructions regarding to the installation.
|-- RobotPlayground_20121227v01.linux.x86.zip - GNU/Linux x86 build.
|-- RobotPlayground_20121227v01.linux.x86_64.zip - GNU/Linux x86_64 build.
|-- RobotPlayground_20121227v01.win32.x86.zip - MS Windows x86 build.
|-- RobotPlayground_20121227v01.win32.x86_64.zip - MS Windows x86_64 build.
|-- RobotPlayground_source_20121227.zip - Snapshot of the source code from
	12-Dec-2012. Archived in zip.
|-- thesis.pdf - The thesis in PDF format.
`-- thesisTextSource.zip - Source code of the thesis. Archived in zip.
\end{lstlisting}
\endgroup